package org.example.springbook.Controller;

import jakarta.servlet.http.HttpSession;
import org.example.springbook.Service.UserService;
import org.example.springbook.constant.Constants;
import org.example.springbook.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.example.springbook.constant.Constants.SESSION_USER_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-06-20
 * Time: 16:39
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Boolean login(String userName, String password, HttpSession session) {
        //检查参数
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }
        //验证账号密码是否正确
        /**
         * if (userName.equals("admin")){ }  这种写法, 如果userName为null, 会报空指针异常
         */
        //1. 根据用户名去查找用户信息
        UserInfo userInfo = userService.getUserInfoByName(userName);
        //2. 比对密码是否正确
        if (userInfo == null || userInfo.getId() <= 0) {
            return false;
        }
        if (password.equals(userInfo.getPassword())) {
            //账号密码正确
            //存Session
            userInfo.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY, userInfo);
            return true;
        }

        //账号密码错误
        return false;
    }
}
